package top.ishowcode.bootweb01.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class ViewTestController {
    @GetMapping("/helloTh")
    public String helloTh(Model model){
        model.addAttribute("msg","hello TH");
        model.addAttribute("link","http://www.baidu.com");
        return "success";
    }
    @GetMapping("/gotoUpload")
    public String gotoUpload(){
        return "InputFile";
    }
    @PostMapping("/login")
    public String login(@RequestParam("email") String email,
                        @RequestParam("password") String password,Model model){
        if (email.equals("")||password.equals("")){
            model.addAttribute("msg","请填写邮箱或密码");
            return "erro";
        }else {
            if (email.equals("3010266295@qq.com")&&password.equals("6235290")){
                model.addAttribute("msg","File Login Success");
                return "success";
            }else {
                model.addAttribute("msg","邮箱或密码错误");
                return "erro";
            }
        }

    }
   @PostMapping("/upload")
    public String upload(@RequestPart("headImage")MultipartFile headImage,
                           @RequestPart("photos") MultipartFile[] photos,
                           Model model
                         ) throws IOException {
       if (!headImage.isEmpty()){
           //保存文件存储器，oss服务器
           String orginFilename = headImage.getOriginalFilename();
           headImage.transferTo(new File("D:\\BCSoftWare\\ideaproject\\SpringBootPro\\boot-web01\\src\\main\\resources\\resources\\upload\\"+orginFilename));
       }
       if (photos.length>0){
           for (MultipartFile photo :photos){
               if (!photo.isEmpty()){
                   String orginFilenamePhoto = photo.getOriginalFilename();
                   photo.transferTo(new File("D:\\BCSoftWare\\ideaproject\\SpringBootPro\\boot-web01\\src\\main\\resources\\resources\\upload\\"+orginFilenamePhoto));
               }
           }
       }
       model.addAttribute("msg","File Upload Success");

        return "FileSuccess";
    }
    @GetMapping("/getAllFile")
    public String getAllFile(Model model){
        List<Object> list = new ArrayList<>();
        File baseFile = new File("D:\\BCSoftWare\\ideaproject\\SpringBootPro\\boot-web01\\src\\main\\resources\\resources\\upload");
        if (baseFile.isFile() || !baseFile.exists()) {
            model.addAttribute("msg","不存在文件夹或文件,请先上传哦");
            return "erroFile";
        }else {
            File[] files = baseFile.listFiles();
            for (File file : files) {
                Map<String, String> map = new HashMap<>();
                if (file.isFile()) {
                    map.put("fileName", file.getName());
                    map.put("filePath", file.getAbsolutePath());
                    float length = (float) file.length()/1048576;
                    String fileSize = String.format("%.2f",length);
                    map.put("fileSize",fileSize);
                    list.add(map);
                }
            }
            model.addAttribute("files",list);
            return "Download";
        }


    }
    @GetMapping("/download")
    public String download(@RequestParam("filePath") String filePath,
                           @RequestParam("fileName") String fileName,
                           Model model, HttpServletResponse response)
                           throws UnsupportedEncodingException {
        File file = new File(filePath);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";filename*=utf-8''"
                    + URLEncoder.encode(fileName, "UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                model.addAttribute("msg",fileName+"下载成功");
            } catch (Exception e) {
                e.printStackTrace();
                model.addAttribute("msg",fileName+"下载失败");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "FileSuccess";
    }

}
